package com.rainripple.java.common.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.rainripple.java.common.log.Log;

public class FileUtil {
	public static File mkdir(String path) {
		File fd = null;
		try {
			fd = new File(path);
			if (!fd.exists()) {
				fd.getParentFile().mkdirs();
			}
		} catch (Exception e) {
			Log.error(e);
		}
		return fd;
	}

	public static byte[] readFile(String path, String name) {

		BufferedInputStream in = null;
		ByteArrayOutputStream out = null;
		byte[] content;
		try {
			File file = new File(path + "/" + name);
			in = new BufferedInputStream(new FileInputStream(file));
			out = new ByteArrayOutputStream(1024);
			byte[] temp = new byte[1024];
			int size = 0;
			while ((size = in.read(temp)) != -1) {
				out.write(temp, 0, size);
			}
			content = out.toByteArray();
			return content;
		} catch (FileNotFoundException e) {
			Log.error(e);
			e.printStackTrace();
		} catch (IOException e) {
			Log.error(e);
		} finally {
			if (null != out) {
				try {
					out.close();

				} catch (IOException e) {
					Log.error(e);
				}
			}
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					Log.error(e);
				}
			}
		}

		return null;
	}

	public static Map<String, String> getFileList(String path, String regex) {
		Map<String, String> mp3Info = new HashMap<String, String>();
		iteration(path, mp3Info, regex);
		return mp3Info;
	}

	private static void iteration(String path, Map<String, String> list, String regex) {
		File f = new File(path);
		if (f.exists()) {
			if (f.isDirectory()) {
				for (String subPath : f.list()) {
					iteration(f.getAbsolutePath() + "/" + subPath, list, regex);
				}
			} else {
				if (regex != null && regex.length() > 0) {
					if (f.getName().matches(regex)) {
						list.put(f.getName(), f.getAbsolutePath());
					}
				}
			}
		} else {
			return;
		}
	}

}
